package net.googlecode.demenkov.utils;

import net.googlecode.demenkov.domains.Person;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.sql.Date;

/**
 * Class-validator for Edit profile action.
 *
 * @author Demenkov Yura
 */
public class PersonValidatorForEditProfile implements Validator {

    @Override
    public boolean supports(Class<?> aClass) {
        return Person.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstname.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "middleName", "middlename.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastname.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bday", "bday.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "group.groupName", "groupname.required");
        Person person = (Person) o;
        if (person.getFirstName().length() > 30) {
            errors.rejectValue("firstName", "firstname.error");
        }
        if (person.getMiddleName().length() > 30) {
            errors.rejectValue("middleName", "middlename.error");
        }
        if (person.getLastName().length() > 30) {
            errors.rejectValue("lastName", "lastname.error");
        }
        if (((person.getPassword().length() > 30) || (person.getPassword().length() < 6)) && (person.getPassword() != "")) {
            errors.rejectValue("password", "password.error");
        }
        if (person.getBday().length() == 1) {
            person.setBday("0" + person.getBday());
        }
        if (person.getBmonth().length() == 1) {
            person.setBmonth("0" + person.getBmonth());
        }
        if (!person.getBday().isEmpty()) {
            try {
                Date date = Date.valueOf(person.getByear() + "-" + person.getBmonth() + "-" + person.getBday());
            } catch (Exception e) {
                errors.rejectValue("bday", "bday.error");
            }
        }
    }
}
